extends Unit
class_name Enemy

@export var flock_push : float = 20.0

@onready var vision_area: Area2D = $VisionArea

var move_dir : Vector2
var can_move : bool  = true

func _process(delta: float) -> void:
	if !can_move :
		return
		
	if !can_move_towards_player() :
		return	
	
	position += get_move_direction() * (50 * delta)
	update_rotation()
	queue_redraw()
	
func get_move_direction() -> Vector2:
	if !is_instance_valid(Global.player) :
		return Vector2.ZERO
		
	var direction := global_position.direction_to(Global.player.global_position)
	for area : Node2D in vision_area.get_overlapping_areas() :
		if area != self && area.is_inside_tree():
			var vector := global_position - area.global_position
			direction += flock_push * vector.normalized() / vector.length()
	return direction
	
func _draw() -> void:
	var direction := get_move_direction()
	var end_position = direction.normalized() * 50
	draw_line(Vector2.ZERO, end_position, Color.BLUE, 1.0)
	draw_circle(end_position, 2.0, Color.BLUE )
	
# 本项目中无需控制旋转（敌人移动时的面朝向）
func update_rotation() -> void :
	pass	
	
func can_move_towards_player() -> bool:
	return is_instance_valid(Global.player) && global_position.distance_to(Global.player.global_position) > 15.0
	
